package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleHtmlTasks {
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IApArticleService apArticleService;

    @Autowired
    private Configuration configuration;
    @Async
    public void createHtml(ApArticle apArticle, String content){
        try {
            Long apArticleId = apArticle.getId();
            //获取数据
            List<Map> mapList = JSON.parseArray(content, Map.class);
            Map dataModel = new HashMap();
            dataModel.put("content",mapList);
            //获取模板
            Template template = configuration.getTemplate("article.ftl");
            //模板与数据模型结合生成html
            StringWriter stringWriter = new StringWriter();
            template.process(dataModel,stringWriter);
            //html放到minio
            ByteArrayInputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
            minIOService.upload("/article/"+apArticleId+".html",inputStream,"text/html");
            //数据库设置staticurl
            apArticle.setStaticUrl("http://192.168.85.143:9000/article/"+apArticleId+".html");
            apArticleService.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
